//!
//! Copyright (c) 2024-2999 北京心月狐科技有限公司 All rights reserved.
//!
//! https://www.mxxshop.com
//!
//! Licensed 并不是自由软件，未经许可不能去掉 MxxShop 相关版权
//!
//! 版权所有，侵权必究！
//!


use rbatis::{Page, PageRequest};
use crate::core::errors::error::{Error, Result};
use crate::modules::product::entity::favorites_entity::Favorites;
use crate::modules::product::entity::favorites_model::{FavoritesSaveRequest, QueryPageBO};
use crate::pool;

pub async fn save_favorites(item: FavoritesSaveRequest) -> Result<u64>{
    let entity: Favorites = item.into();
    // 启动一个事务
    let mut tx = pool!().acquire_begin().await?;
    let result = Favorites::insert(&tx, &entity).await?;
    return if result.rows_affected > 0 {
        tx.commit().await?;
        tx.rollback().await?;
        Ok(result.rows_affected)
    }else{
        Ok(0)
    }
}

pub async fn batch_delete(ids: Vec<String>) -> Result<u64>{
    let mut tx = pool!().acquire_begin().await?;
    let result = Favorites::delete_in_column(&tx, "id", &ids).await?;
    return if result.rows_affected > 0 {
        tx.commit().await?;
        tx.rollback().await?;
        Ok(result.rows_affected)
    }else{
        Ok(0)
    }
}

pub async fn get_page_list(item: QueryPageBO) -> Result<Page<Favorites>>{
    let page_req = &PageRequest::new(item.page_num.clone().unwrap_or_default(), item.page_size.clone().unwrap_or_default());
    let result = Favorites::select_by_page(pool!(), page_req, &item).await?;
    return Ok(result);
}